package com.uuah.server.config.spring.parsers.generic;

import java.util.concurrent.atomic.AtomicInteger;

import org.w3c.dom.Element;

import com.uuah.server.config.spring.parsers.AbstractUuahBeanDefinitionParser;
import com.uuah.utils.StringUtils;

public class AutoIdUtils {

	public static final String ATTRIBUTE_ID = AbstractUuahBeanDefinitionParser.ATTRIBUTE_ID;
	public static final String ATTRIBUTE_NAME = AbstractUuahBeanDefinitionParser.ATTRIBUTE_NAME;
	private static final AtomicInteger counter = new AtomicInteger(0);
	public static final String PREFIX = "com.uuah.autogen.";

	public static boolean blankAttribute(Element element, String attribute) {
		return StringUtils.isBlank(element.getAttribute(attribute));
	}

	public static void ensureUniqueId(Element element, String type) {
		if (null != element && blankAttribute(element, ATTRIBUTE_ID)) {
			if (blankAttribute(element, ATTRIBUTE_NAME)) {
				element.setAttribute(ATTRIBUTE_ID, uniqueValue(PREFIX + type));
			} else {
				element.setAttribute(ATTRIBUTE_ID, element
						.getAttribute(ATTRIBUTE_NAME));
			}
		}
	}

	public static String getUniqueName(Element element, String type) {
		if (!blankAttribute(element, ATTRIBUTE_NAME)) {
			return element.getAttribute(ATTRIBUTE_NAME);
		} else if (!blankAttribute(element, ATTRIBUTE_ID)) {
			return element.getAttribute(ATTRIBUTE_ID);
		} else {
			return uniqueValue(PREFIX + type);
		}
	}

	public static String uniqueValue(String value) {
		return value + "." + counter.incrementAndGet();
	}

	public static void forceUniqueId(Element element, String type) {
		if (null != element) {
			String id = uniqueValue(PREFIX + type);
			element.setAttribute(ATTRIBUTE_ID, id);
			element.setAttribute(ATTRIBUTE_NAME, id);
		}
	}

}
